package com.umgsai.wx.backend.test.map;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

public class LRU {

    public LRU() {

    }

    public LRU(int maxSize) {
        super();
        this.maxSize = maxSize;
    }

    private int maxSize = 0;

    LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<>();

    public String get(String key) {
        String value = linkedHashMap.remove(key);
        if (value != null) {
            linkedHashMap.put(key, value);
            return value;
        }
        return null;
    }

    public void put(String key, String value) {
        linkedHashMap.put(key, value);
        if (linkedHashMap.size() > maxSize) {
            String removeKey = null;
            for (Map.Entry<String, String> entry : linkedHashMap.entrySet()) {
                removeKey = entry.getKey();
                break;
            }
            linkedHashMap.remove(removeKey);
        }
    }

    private void print(LinkedHashMap<String, String> linkedHashMap) {
        System.out.println("========================");
        Set<Map.Entry<String, String>> entrySet = linkedHashMap.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue();
            System.out.printf("key=%s value=%s\n", key, value);
        }
    }

    public static void main(String[] args) {
        LRU lru = new LRU(5);
        for (int i = 1; i <= 5; i++) {
            lru.put(String.valueOf(i), String.valueOf(i));
        }
        lru.get("3");
        lru.get("1");
        lru.put("6", "6");
        lru.print(lru.linkedHashMap);
    }
}
